package com.yehee.chainserver.init;

import com.yehee.chainserver.common.BaseChainServer;
import com.yehee.chainserver.mapper.ChainDepositMapper;
import com.yehee.chainserver.mapper.ChainWithdrawMapper;
import com.yehee.chainserver.server.EthChainServer;
import com.yehee.chainserver.util.NetUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.Ordered;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 服务运行和监控
 * @author wx
 * @create 2019-01-21 12:43
 **/
@Log4j2
@Component
public class GlobalChain implements ApplicationRunner, Ordered {

    @Value("${server.port}")
    public String port;


    @Autowired
    ChainDepositMapper colaChainDepositMapper;

    @Autowired
    ChainWithdrawMapper withdrawMapper;
    @Autowired
    EthChainServer ethChainServer;

    public static final Map<String, BaseChainServer> serverMap = new HashMap<>();

    public static String JAR_PATH;

    @Override
    public int getOrder() {
        return 1;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        JAR_PATH = getJarPath();

        try {

            ethChainServer.run();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(()->startModule());
    }

    /**
     * 启动
     */
    private void startModule(){


    }

    /**
     * 监控 server 运行情况
     */
    @Scheduled(cron = "0/30 * * * * ?")
    public void monitor(){

    }

    /**
     * 推送未被处理的充值
     * @param module
     */
    public void unRecord(String module){

    }


    /**
     * 处理提币
     * 1 获取属于当前服务的订单
     * 2 循环处理订单,并发送处理结果
     *
     */
    @Scheduled(cron = "30 0/1 * * * ?")
    public void dealExportedWithdraw() throws Throwable{

    }


    private String getHost(){
        return NetUtil.getLocalIpAddress();
    }

    private static String getJarPath(){
        ApplicationHome home = new ApplicationHome(GlobalChain.class);
        File jarFile = home.getDir();
        return jarFile.getParent();
    }

}
